package com.dqp.cslggroup.ConnectNet;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dqp.cslggroup.UI.MyApplication;
import com.dqp.cslggroup.Util.SharedPreferencesUtil;
import com.dqp.cslggroup.Util.verification;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;


public class connectJWXT {
    private String url;
    private Map<String, String> cookies;
    private String modulus;
    private String exponent;
    private String csrftoken;
    private Connection connection;
    private Connection.Response response;
    private Document document;
    private String stuNum;
    private String password;
    private String yz;
    private Map<String, String> cookie;
    private String Authorization = SharedPreferencesUtil.getStringSp(MyApplication.getContext(), "Authorization", "");
    private int i;
    private String userAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36";

    public connectJWXT(String url, String stuNum, String password) {
        this.url = url;
        this.stuNum = stuNum;
        this.password = password;
    }

    public void vpninit() {
        getvpnCookie();
    }

    public void init() {
        getCsrftoken();
        getRSApublickey();
    }

    public Map<String, String> sendCookie() {
        //传出cookies
        return cookies;
    }

    public String sendmodulus() {
        //传出数据
        return modulus;

    }

    public String sendexponent() {
        //传出数据
        return exponent;
    }

    public int sendcheck_i() {
        //传出数据
        return i;
    }

    public Map<String, String> getCookies() {
        return cookie;

    }

    public void accptCookie(Map<String, String> cookies) {
        this.cookies = cookies;
    }

    public void acctKey(String a, String b) {
        this.modulus = a;
        this.exponent = b;
    }

    public void acctyzm(String yzm) {
        this.yz = yzm;
    }

    private void getvpnCookie() {
        try {
            response = Jsoup.connect("http://login.cslg.vpn358.com/index.php")
                    .ignoreContentType(true) // 获取图片需设置忽略内容类型
                    .userAgent("Mozilla")
                    .method(Connection.Method.GET)
                    .timeout(5000)
                    .execute();
            cookie = response.cookies();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public int getLoginXXMH() {
       /* connection = Jsoup.connect("http://login.cslg.vpn358.com/index.php?r=front/logincheck");
        connection.header("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        connection.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
        connection.data("r", "front/logincheck");
        connection.data("password", password);
        connection.data("username", stuNum);
        connection.cookies(cookie)
                .ignoreContentType(true)
                .method(Connection.Method.POST)
                .timeout(5000)
                .execute();
        response = connection.execute();
        cookie = response.cookies();
        document = Jsoup.parse(response.body());
        JSONObject jsonObject = JSON.parseObject(response.body());
        error = jsonObject.getString("status");*/

        try {
            connection = Jsoup.connect("http://login.cslg.vpn358.com/index.php?r=front/login");
            connection.header("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            connection.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
            connection.data("r", "front/couples_login");
            connection.data("password", password);
            connection.data("username", stuNum);
            connection.cookies(cookie)
                    .ignoreContentType(true)
                    .method(Connection.Method.POST)
                    .timeout(5000)
                    .execute();
            response = connection.execute();
            document = Jsoup.parse(response.body());
            String error = document.toString();
            cookie = response.cookies();
            if (error.contains("error")) {
                return 2;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 1;

    }

    public void getvpnRSApublickey() {
     /* connection = Jsoup.connect("http://login.cslg.vpn358.com/index.php?pre=http%3A%2F%2F10.28.200.191.cslg.vpn358.com%2Fjwglxt%2Fxtgl%2Flogin_slogin.html");
        connection.header("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        connection.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
        connection.data("pre", "http://10.28.200.191.cslg.vpn358.com/jwglxt/xtgl/login_slogin.html");
        connection.cookies(cookies).ignoreContentType(true)
                .method(Connection.Method.POST)
                .timeout(3000)
                .execute();
        response = connection.execute();
        document = Jsoup.parse(response.body());
        cookie = response.cookies();
        //保存csrftoken
        //csrftoken = document.getElementById("csrftoken").val();
        csrftoken = document.select("input[name=csrftoken]").val();*/

        try {
            response = Jsoup.connect("http://10.28.200.191.cslg.vpn358.com/jwglxt/xtgl/login_getPublicKey.html?time=" + new Date().getTime() + "&_=" + new Date().getTime())
                    .cookies(cookies)
                    .ignoreContentType(true)
                    .timeout(5000)
                    .execute();
            cookie = response.cookies();
            JSONObject jsonObjects = JSON.parseObject(response.body());
            modulus = jsonObjects.getString("modulus");
            exponent = jsonObjects.getString("exponent");
            document = Jsoup.parse(response.body());
            String JSESSIONID = cookie.get("JSESSIONID");
            cookies.remove("PHPSESSID");
            cookies.put("JSESSIONID", JSESSIONID);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public int vpnLogin() {
        try {
            password = RSAEncoder.RSAEncrypt(password, B64.b64tohex(modulus), B64.b64tohex(exponent));
            password = B64.hex2b64(password);
            connection = Jsoup.connect(url);
            connection.header("Content-Type", "text/html;charset=UTF-8");
            connection.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
            connection.data("csrftoken", "");
            connection.data("yhm", stuNum);
            connection.data("mm", password);
            connection.data("mm", password);
            connection.data("yzm", yz);
            connection.cookies(cookies)
                    .ignoreContentType(true)
                    .method(Connection.Method.POST)
                    .timeout(5000)
                    .execute();
            response = connection.execute();
            document = Jsoup.parse(response.body());
            if (document.getElementById("tips") == null) {

                return 1;
            } else if (document.getElementById("tips").text().contains("用户名或密码不正确")) {
                return 2;
            } else if (document.getElementById("tips").text().contains("验证码输入错误")) {
                return 3;
            } else if (document.getElementById("tips").text().contains("验证码不能为空")) {
                return 4;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

    private void getCsrftoken() {
        try {
            response = Jsoup.connect(url + "/jwglxt/xtgl/login_slogin.html?language=zh_CN&_t=" + new Date().getTime())
                    .method(Connection.Method.GET)
                    .userAgent("Mozilla")
                    .header("Authorization", Authorization)
                    .execute();
            cookies = response.cookies();
            /*response = Jsoup.connect(url + "/jwglxt/xtgl/login_slogin.html?language=zh_CN&_t=" + new Date().getTime())
                    .ignoreContentType(true) // 获取图片需设置忽略内容类型
                    .userAgent("Mozilla")
                    .cookies(cookies)
                    .method(Connection.Method.GET)
                    .timeout(10000)
                    .execute();
            cookies = response.cookies();*/
            document = Jsoup.parse(response.body());
            csrftoken = document.getElementById("csrftoken").val();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getRSApublickey() {
        try {
            response = Jsoup.connect(url + "/jwglxt/xtgl/login_getPublicKey.html?" + "time=" + new Date().getTime())
                    .cookies(cookies)
                    .method(Connection.Method.GET)
                    .header("Authorization", Authorization)
                    .ignoreContentType(true)
                    .timeout(10000)
                    .execute();
            JSONObject jsonObject = JSON.parseObject(response.body());
            document = Jsoup.parse(response.body());
            modulus = jsonObject.getString("modulus");
            exponent = jsonObject.getString("exponent");
            password = RSAEncoder.RSAEncrypt(password, B64.b64tohex(modulus), B64.b64tohex(exponent));
            password = B64.hex2b64(password);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public int loginByJsoup() throws IOException {
        Connection connection = Jsoup.connect(url + "/jwglxt/xtgl/login_slogin.html");
        Connection.Response response = connection.userAgent(userAgent).header("Authorization", Authorization).ignoreContentType(true).method(Connection.Method.GET).timeout(5000).execute();
        if (response.statusCode() == 200) {
            cookies = response.cookies();
            document = Jsoup.parse(response.body());
            connection.url(url + "/jwglxt/xtgl/login_getPublicKey.html?" + "time=" + new Date().getTime() + "&_t" + new Date().getTime());
            response = connection.ignoreContentType(true).userAgent(userAgent).header("Authorization", Authorization).method(Connection.Method.GET).cookies(cookies).timeout(5000).execute();

            if (response.statusCode() == 200) {
                JSONObject ras = JSON.parseObject(response.body());
                String modulus = ras.getString("modulus");
                String exponent = ras.getString("exponent");
                password = RSAEncoder.RSAEncrypt(password, B64.b64tohex(modulus), B64.b64tohex(exponent));
                password = B64.hex2b64(password);

                List<Element> et = document.select("form");
                Map<String, String> datas = new IdentityHashMap<>();
                for (Element e : et.get(0).getAllElements()) {
                    if (e.attr("name").equals("yhm")) {
                        e.attr("value", stuNum);// 设置用户名
                    }
                    if (e.attr("name").equals("mm")) {
                        e.attr("value", password); // 设置用户密码
                    }
                    if (e.attr("name").equals("csrftoken")) {
                        csrftoken = e.attr("value"); // 设置用户密码
                    }
                    if (e.attr("name").length() > 0) {// 排除空值表单属性
                        datas.put(e.attr("name"), e.attr("value"));
                    }
                }

                connection.url(url + "/jwglxt/xtgl/login_slogin.html?time=" + new Date().getTime());
                Connection.Response login = connection.ignoreContentType(true).method(Connection.Method.POST)
                        .data(datas)
                        .cookies(cookies)
                        .userAgent(userAgent)
                        .header("Authorization", Authorization)
                        .followRedirects(true)
                        .execute();
                //Log.e("url", login.url().toString());
                if (response.statusCode() == 200) {
                    if (login.url().toString().contains("index_initMenu.html")) {
                        Map<String, String> map = login.cookies();
                        String JSESSIONID = map.get("JSESSIONID");
                        cookies.put("JSESSIONID", JSESSIONID);
                        return 1;
                    } else if (login.url().toString().contains("login_slogin")) {
                        Document document = Jsoup.parse(login.body());
                        String tips = document.getElementById("tips").text();
                        if (tips == null) {
                            return 1;
                        } else if (tips.contains("用户名或密码不正确")) {
                            return 2;
                        } else if (tips.contains("验证码输入错误")) {
                            return 3;
                        } else if (tips.contains("验证码不能为空")) {
                            return 4;
                        }
                    } else {
                        cookies.put("tips", "登录失败！");
                    }
                }
            }
        }
        return 0;
    }


    public int beginLogin() {
        try {
            response = Jsoup.connect(url + "/jwglxt/xtgl/login_slogin.html")
                    .ignoreContentType(true) // 获取图片需设置忽略内容类型
                    .cookies(cookies)
                    .userAgent("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36")
                    .header("Authorization", Authorization)
                    .method(Connection.Method.POST)
                    .data("yhm", stuNum)
                    .data("mm", password)
                    .data("mm", password)
                    .timeout(10000)
                    .execute();
            document = Jsoup.parse(response.body());
            cookies = response.cookies();
            if (document.getElementById("tips") == null) {
                return 1;
            } else if (document.getElementById("tips").text().contains("用户名或密码不正确")) {
                return 2;
            } else if (document.getElementById("tips").text().contains("验证码输入错误")) {
                return 3;
            } else if (document.getElementById("tips").text().contains("验证码不能为空")) {
                return 4;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

}
